﻿using System;
using System.Collections.Generic;
using PivotServerTools;

namespace CollectionFactories.TeamCity
{
    public class TeamCityCollectionFactory : CollectionFactoryBase
    {
        private readonly IEnumerable<ITeamCityCollectionFactory> collectionFactories;

        public TeamCityCollectionFactory()
        {
            collectionFactories = new ITeamCityCollectionFactory[]
                                      {
                                          new TeamCityProjectsCollectionFactory(new TeamCityBuildTypesCollectionFactory(new TeamCityBuildsCollectionFactory())),
                                          new TeamCityBuildTypesCollectionFactory(new TeamCityBuildsCollectionFactory()),
                                          new TeamCityBuildsCollectionFactory()
                                      };

            Summary = "Get data from TeamCity";
            SampleQueries = new[]
                                {
                                    "serverUrl=http://teamcity.jetbrains.com&guest=1",
                                    "serverUrl=http://localhost:81&username=simone&password=simone",
                                };
        }

        public override Collection MakeCollection(CollectionRequestContext context)
        {
            foreach (var factory in collectionFactories)
            {
                if (factory.CanHandle(context))
                    try
                    {
                        return factory.Handle(context);
                    }
                    catch (Exception e)
                    {
                        return ErrorCollection.FromException(e);
                    }
            }

            return ErrorCollection.FromException(new ArgumentException("What do you want to know exactly?"));
        }
    }
}